;(function (document, Socket) {
  const OList = document.querySelector('#list')
  const OMsg = document.querySelector('#message')
  const send = document.querySelector('#send')
  const ws = new Socket('ws:localhost:8000')
  const init = () => {
    bindEvent()
  }
  let username = ''

  const bindEvent = function () {
    send.addEventListener('click', onSend)
    ws.addEventListener('open', onOpen)
    ws.addEventListener('close', onClose)
    ws.addEventListener('error', onError)
    ws.addEventListener('message', onMessage)
  }

  const onSend = (e) => {
    const msg = OMsg.value
    console.log('onSend', e)
    if (!msg.trim().length) {
      return
    }
    ws.send(
      JSON.stringify({
        user: username,
        dateTime: new Date().getTime(),
        msg: msg,
      })
    )

    // OMsg.value = ''
  }
  const onOpen = (e) => {
    console.log('onOpen', e)
    username = localStorage.getItem('nickname')
    if (!username) {
      location.href = 'entry.html'
      return
    }
  }
  const onClose = (e) => {
    console.log('onClose', e)
  }
  const onMessage = (e) => {
    console.log('onMessage', e)
    const message = JSON.parse(e.data)
    console.log('message', message)
    addList(message)
  }
  const onError = (e) => {
    console.log('onError', e)
  }
  function addList(message) {
    let { user, dateTime, msg } = message
    dateTime = formatDate(dateTime)
    const OLi = document.createElement('li')
    OLi.innerHTML = `<p><em>昵称:${user}</em>  <em> 时间:${dateTime}</em> </p>
                     <p> 信息:${msg}</p>`

    OList.appendChild(OLi)
  }
  function formatDate(d) {
    const date = new Date(d)
    Y = date.getFullYear() + '-'
    M =
      (date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1) + '-'
    D = date.getDate() + ' '
    h = date.getHours() + ':'
    m = date.getMinutes() + ':'
    s = date.getSeconds()
    return Y + M + D + h + m + s
  }

  init()
})(document, WebSocket)
